home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 629 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.0 KB  |  88 lines

  1. Path: mainframe.webgenesis.com!user
  2. From: vance@webgenesis.com (Vance Huntley)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How best to handle constructor failure?
  5. Date: Fri, 05 Jan 1996 08:52:05 -0500
  6. Organization: WebGenesis, Inc.
  7. Sender: vrh1@cornell.edu (Verified)
  8. Message-ID: <vance-0501960852050001@mainframe.webgenesis.com>
  9. References: <4c36gl$5e5@nnrp1.news.primenet.com> <4cimnp$hne@news1.panix.com>
  10. NNTP-Posting-Host: mainframe.webgenesis.com
  11. X-Newsreader: Value-Added NewsWatcher 2.1d3+
  12.  
  13. >  I noticed that there was another thread on constructors that was
  14. recently posted,
  15. > where a suggestion was made to use a seperate initialization function
  16. (what I called
  17. > a "test" method").  I have done this upon occasion, but I need to
  18. overload operators,
  19. > and hence there will be compiler-generated, implicit constructor calls
  20. which would
  21. > not include execution of the seperate initializer method!  The issue of
  22. dealing with
  23. > constructors that can fail appears to be a complex one.  Perhaps a good thread
  24. > will start on the subject!.
  25.  
  26.  
  27. One (not very elegant) solution I have used in the past (when my compiler
  28. didn't support exceptions goes like this:
  29.  
  30. class ValidatedObject
  31. {
  32. public:
  33.    CanFailObject() { mIsValid = false; }
  34.  
  35.    Boolean IsValid() { return mIsValid; }
  36.  
  37.    void Invalidate() { mIsValid = false; }
  38.  
  39.    void Validate() { mIsValid = true; }
  40.  
  41. private:
  42.    Boolean mIsValid;
  43. };
  44.  
  45.  
  46.  
  47. class AnObject : public ValidatedObject
  48. {
  49.    AnObject();
  50.  
  51.    void CriticalOperation();
  52. };
  53.  
  54.  
  55.  
  56. AnObject::AnObject()
  57. {
  58.    // do lots of allocation and other things that may well fail
  59.  
  60.    if(  all of the stuff above was sucessfull )
  61.       Validate();
  62. }
  63.  
  64.  
  65.  
  66. AnObject::CriticalOperation()
  67. {
  68.    if( IsValid() )
  69.       {
  70.       // do stuff that would have crashed my machine if the
  71.       // object was poorly constructed
  72.       }
  73.    else
  74.       {
  75.       // do some error handling
  76.       }
  77.  
  78. }
  79.  
  80.  
  81. This works, in general, even for objects derived from AnObject.
  82.  
  83. Now that I work in a compiler environment which supports exceptions, I use
  84. them happily and often.
  85.  
  86. Vance
  87.